//
//  LandscapeTableView.m
//  ColumnWidget
//
//  Created by -_Asuna on 16/8/12.
//  Copyright © 2016年 David. All rights reserved.
//

#import "LandscapeTableView.h"

enum ScrollDirection{
    ScrollStop,
    ScrollToRight,
    ScrollToLeft
};

@implementation LandscapeTableView{
    CGFloat _startOffset;
    enum ScrollDirection _scrollDirection;
    NSInteger _scrollingIndex;
}

#pragma mark- init method
-(instancetype)init{
    self=[super init];
    if(self){
        [self initSets];
    }
    return self;
}
-(instancetype)initWithFrame:(CGRect)frame{
    self=[super initWithFrame:frame];
    if(self){
        [self initSets];
    }
    return self;
}
-(instancetype)initWithCoder:(NSCoder *)aDecoder{
    self=[super initWithCoder:aDecoder];
    if(self){
        [self initSets];
    }
    return self;
}
-(void)initSets{
    _scrollView=[[UIScrollView alloc] initWithFrame:self.bounds];
    _scrollView.pagingEnabled=YES;
    _scrollView.showsHorizontalScrollIndicator=NO;
    _scrollView.showsVerticalScrollIndicator=NO;
    _scrollView.delegate=self;
    _leftVisibleIndex=-1;
    _rightVisibleIndex=1;
    _currentIndex=0;
    _newIndex=-1;
    _preLoad=1;
    _isScrolling=NO;
    _scrollDirection=ScrollStop;
    _reusableCells=[NSMutableSet set];
    _scrollingIndex=0;
     [self addSubview:_scrollView];
}
-(void)setContent{
    _cellCounts=[_dateSource numberOfCells];
    CGSize size=CGSizeMake(_cellCounts*CGRectGetWidth(_scrollView.bounds), 0);
    _scrollView.contentSize=size;
    [_delegate tableViewDidBeginScrollingFromIndex:0 ToIndex:0 offset:[self bounds].size.width/2];
    [_delegate tableViewDidChangePageWithIndex:0];
    [self configureCells];
}
#pragma mark- property methods
//确保两边预加载的cell大于1
-(void)setPreLoad:(NSUInteger)preLoad{
    if(preLoad<=0)
        return ;
    _preLoad=preLoad;
}
-(void)setDateSource:(id<LandscapeTableViewDataSource>)dateSource{
    _dateSource=dateSource;
    [self setContent];
}
-(void)setCurrentIndex:(NSInteger)currentIndex{
    _currentIndex=currentIndex;
    if(!_isScrolling)
        [_delegate tableViewDidChangePageWithIndex:currentIndex];
}


#pragma mark- cell methods
-(void)configureCells{
    if(_newIndex==_currentIndex)
        return ;
    if(_newIndex!=-1)
    self.currentIndex=_newIndex;

    //找到需要加载的两个边界index
    if(!_isScrolling){
        _leftVisibleIndex=_currentIndex-1;
        _rightVisibleIndex=_currentIndex+1;
    }
    NSInteger left=MAX(MIN(_leftVisibleIndex, _currentIndex-_preLoad),0);
    NSInteger right=MIN(_cellCounts-1,MAX(_rightVisibleIndex,_currentIndex+_preLoad));
    //将超过边界的cell回收
    if(!_isScrolling){
        for(NSInteger index=0;index<_cellCounts;index++){
            UIView *view=[_scrollView viewWithTag:index+100];
            if(index<left||index>right){
                if(view){
                    [_reusableCells addObject:view];
                    [view removeFromSuperview];
                }
            }else{
                if(!view){
                    UIView *cell=[_dateSource cellAtIndex:index];
                    [_scrollView addSubview:cell];
                }
            }
        }
     //   NSLog(@"subviews %ld",[_scrollView subviews].count);
    }
    
}

-(UIView *)dequeueReusableCell{
    UIView *cell=[_reusableCells anyObject];
    if(cell)
    [_reusableCells removeObject:cell];
    return cell;
}
#pragma mark- delegateWillCall
-(void)setLocationWithIndex:(NSUInteger)index{
    [_scrollView setContentOffset:CGPointMake(index*CGRectGetWidth(_scrollView.bounds), 0)];
    _newIndex=index;
    _isScrolling=NO;
    [self configureCells];
}

-(void)willChangePage{
    NSInteger  rightIndex=MIN(floorf((CGRectGetMaxX(_scrollView.bounds)-1)/CGRectGetWidth(_scrollView.bounds)),_cellCounts-1);
    NSInteger  leftIndex=MAX(floorf((CGRectGetMinX(_scrollView.bounds))/CGRectGetWidth(_scrollView.bounds)),0);
    if(rightIndex>7||leftIndex<0)
        NSLog(@"catch");
    if(_startOffset>0&&_startOffset<[_scrollView contentSize].width-[_scrollView bounds].size.width&&rightIndex!=leftIndex){
        CGFloat offset=_startOffset-_currentIndex*CGRectGetWidth(_scrollView.bounds);
        //左滑
        if((_scrollDirection==ScrollStop&&_startOffset>_scrollView.contentOffset.x)||_scrollDirection==ScrollToLeft){
            //判断当前视图是否偏左
            if([_scrollView contentOffset].x>_currentIndex*CGRectGetWidth(_scrollView.bounds)){
                _scrollDirection=ScrollToRight;
                return ;
            }
            [_delegate tableViewDidBeginScrollingFromIndex:rightIndex ToIndex:leftIndex offset:ABS(offset)];
            _scrollDirection=ScrollToLeft;
        }
         //右滑
        if((_scrollDirection==ScrollStop&&_startOffset<_scrollView.contentOffset.x)||_scrollDirection==ScrollToRight){
            //判断当前视图是否偏右
            if([_scrollView contentOffset].x<_currentIndex*CGRectGetWidth(_scrollView.bounds)){
                _scrollDirection=ScrollToLeft;
                return ;
            }
            [_delegate tableViewDidBeginScrollingFromIndex:leftIndex ToIndex:rightIndex offset:ABS(offset)];
            _scrollDirection=ScrollToRight;
        }
    }
    
    _startOffset=_scrollView.contentOffset.x;
}

#pragma mark- srollView delegate


//视图滑动
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self willChangePage];
    if(!_isScrolling)
        _isScrolling=YES;
    [self configureCells];
}
//
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    _startOffset=_scrollView.contentOffset.x;
}
//手指离开
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if(!decelerate){
        _isScrolling=NO;
        [self configureCells];
    }
}
//停止滑动
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    _isScrolling=NO;
    _newIndex=floorf(CGRectGetMidX(_scrollView.bounds)/CGRectGetWidth(_scrollView.bounds));
    [self configureCells];
    _scrollDirection=ScrollStop;
}



@end









